<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <!-- 公司 -->
        <TreeTools
          :node-date="company"
          :is-root="true"
          @addDepartments="addDepartments"
        />
        <!-- 相关部门 -->
        <el-tree
          :data="departs"
          default-expand-all
          :expand-on-click-node="false"
        >
          <template #default="{data}">
            <TreeTools
              :node-date="data"
              @addDepartments="addDepartments"
              @delDepartments="getDepartments"
              @editDepartments="editDepartments"
            />
          </template>
        </el-tree>
      </el-card>
      <AddDept
        ref="addDept"
        :show-dialog.sync="showDialog"
        :node-date="nodeDate"
        @getDepartments="getDepartments"
      />
    </div>
  </div>
</template>

<script>
import { getDepartments } from '@/api/departments'
import TreeTools from './components/tree-tools.vue'
import AddDept from './components/add-dept.vue'

export default {
  components: {
    TreeTools,
    AddDept
  },
  data() {
    return {
      company: {
        name: '江苏传智播客教育科技股份有限公司',
        manager: '负责人'
      },
      departs: [],
      showDialog: false,
      nodeDate: {}
    }
  },
  created() {
    // 获取公司部门信息
    this.getDepartments()
  },
  methods: {
    // 获取公司部门信息
    async getDepartments() {
      const { depts } = await getDepartments()
      // console.log(depts)
      this.departs = this.listToTreeData(depts, '')
    },
    // 遍历筛选部门的子部门
    listToTreeData(list, pid) {
      // // 算法一  递归方法
      // const res = []
      // list.forEach(item => {
      //   if (item.pid === pid) {
      //     res.push(item)
      //     item.children = this.listToTreeData(list, item.id)
      //   }
      //   // console.log(res)
      // })
      // return res

      // 算法二 非递归方法
      list.forEach(item => {
        if (item.pid !== pid) {
          const parent = list.find(it => it.id === item.pid)
          if (parent) {
            parent.children = parent.children || []
            parent.children.push(item)
          }
        }
      })
      return list.filter(item => item.pid === pid)
    },
    // 编辑部门信息
    async editDepartments(nodeDate) {
      // console.log(nodeDate)
      this.nodeDate = nodeDate
      await this.$refs.addDept.DepartmentDetails(nodeDate.id)
      this.showDialog = true
    },
    // 控制showDialog 弹窗显示
    addDepartments(data) {
      this.nodeDate = data
      // console.log(this.nodeDate)
      this.showDialog = true
    }
  }
}
</script>

<style scoped>
/* .tree-card {
  padding: 30px  140px;
  font-size:14px;
} */
</style>
